<html lang="en-US">

<head>
    
<title>Go 面试官：Go interface 的一个 “坑” 及原理分析 - 花落雨忧</title>

<meta property="og:title" content="Go 面试官：Go interface 的一个 “坑” 及原理分析 - 花落雨忧">



    



    
    <meta property="description" content="大家好，我是煎鱼。
前几天在读者交流群里看到一位小伙伴，针对 interface 的使用有了比较大的疑惑。
无独有偶，我也在网上看到有小伙伴在 Go 面试的时候被问到了：
今天特意分享出来让大家避开这个坑。
[&amp;hellip;] 第一个例子，如下代码：
[&amp;hellip;] func main() { var v interface{} v = (*int)(nil) fmt.Println(v &amp;hellip;">
    <meta property="og:description" content="大家好，我是煎鱼。
前几天在读者交流群里看到一位小伙伴，针对 interface 的使用有了比较大的疑惑。
无独有偶，我也在网上看到有小伙伴在 Go 面试的时候被问到了：
今天特意分享出来让大家避开这个坑。
[&amp;hellip;] 第一个例子，如下代码：
[&amp;hellip;] func main() { var v interface{} v = (*int)(nil) fmt.Println(v &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.site/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.site/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.site/js/jquery.min.js"></script>




<link href="https://www.lican.site/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>
        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/go/go-tips-interface/">Go 面试官：Go interface 的一个 “坑” 及原理分析</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2021/04/05</a>
                                            
                                            
                                            
                                            
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <p>大家好，我是煎鱼。</p>
<p>前几天在读者交流群里看到一位小伙伴，针对 interface 的使用有了比较大的疑惑。</p>
<p>无独有偶，我也在网上看到有小伙伴在 Go 面试的时候被问到了：</p>
<p><img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/36d7ecb0da9e4b32a493dedce6ebc691~tplv-k3u1fbpfcp-watermark.image" alt="来自网上博客的截图"></p>
<p>今天特意分享出来让大家避开这个坑。</p>
<h2 id="例子一">例子一</h2>
<p>第一个例子，如下代码：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-golang" data-lang="golang"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
    <span style="color:#66d9ef">var</span> <span style="color:#a6e22e">v</span> <span style="color:#66d9ef">interface</span>{}
    <span style="color:#a6e22e">v</span> = (<span style="color:#f92672">*</span><span style="color:#66d9ef">int</span>)(<span style="color:#66d9ef">nil</span>)
    <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#a6e22e">v</span> <span style="color:#f92672">==</span> <span style="color:#66d9ef">nil</span>)
}
</code></pre></div><p>你觉得输出结果是什么呢？</p>
<p>答案是：</p>
<pre><code>false
</code></pre><p>为什么不是 <code>true</code>。明明都已经强行置为 <code>nil</code> 了。是不是 Go 编译器有问题？</p>
<h2 id="例子二">例子二</h2>
<p>第二个例子，如下代码：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-golang" data-lang="golang"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
    <span style="color:#66d9ef">var</span> <span style="color:#a6e22e">data</span> <span style="color:#f92672">*</span><span style="color:#66d9ef">byte</span>
    <span style="color:#66d9ef">var</span> <span style="color:#a6e22e">in</span> <span style="color:#66d9ef">interface</span>{}

    <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#a6e22e">data</span>, <span style="color:#a6e22e">data</span> <span style="color:#f92672">==</span> <span style="color:#66d9ef">nil</span>)
    <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#a6e22e">in</span>, <span style="color:#a6e22e">in</span> <span style="color:#f92672">==</span> <span style="color:#66d9ef">nil</span>)

    <span style="color:#a6e22e">in</span> = <span style="color:#a6e22e">data</span>
    <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#a6e22e">in</span>, <span style="color:#a6e22e">in</span> <span style="color:#f92672">==</span> <span style="color:#66d9ef">nil</span>)
}
</code></pre></div><p>你觉得输出结果是什么呢？</p>
<p>答案是：</p>
<pre><code>&lt;nil&gt; true
&lt;nil&gt; true
&lt;nil&gt; false
</code></pre><p>这可就更奇怪了，为什么刚刚声明出来的 <code>data</code> 和 <code>in</code> 变量，确实是输出结果是 <code>nil</code>，判断结果也是 <code>true</code>。</p>
<p>怎么把变量 <code>data</code> 一赋予给变量 <code>in</code>，世界就变了？输出结果依然是 <code>nil</code>，但判定却变成了 <code>false</code>。</p>
<p>和上面的第一个例子结果类似，真是神奇。</p>
<h2 id="原因">原因</h2>
<p>interface 判断与想象中不一样的根本原因是，interface 并不是一个指针类型，虽然他看起来很像，以至于误导了不少人。</p>
<p>我们钻下去 interface，interface 共有两类数据结构：</p>
<p><img src="https://imgkr2.cn-bj.ufileos.com/560dcab5-e436-4a2c-bfee-6eba6faee1d2.png?UCloudPublicKey=TOKEN_8d8b72be-579a-4e83-bfd0-5f6ce1546f13&amp;Signature=HF1wka8F9MTc%252FVCTrMjhASpeeE4%253D&amp;Expires=1615900476" alt=""></p>
<ul>
<li><code>runtime.eface</code> 结构体：表示不包含任何方法的空接口，也称为 empty interface。</li>
<li><code>runtime.iface</code> 结构体：表示包含方法的接口。</li>
</ul>
<p>看看这两者相应的底层数据结构：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-golang" data-lang="golang"><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">eface</span> <span style="color:#66d9ef">struct</span> {
    <span style="color:#a6e22e">_type</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">_type</span>
    <span style="color:#a6e22e">data</span>  <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Pointer</span>
}

<span style="color:#66d9ef">type</span> <span style="color:#a6e22e">iface</span> <span style="color:#66d9ef">struct</span> {
    <span style="color:#a6e22e">tab</span>  <span style="color:#f92672">*</span><span style="color:#a6e22e">itab</span>
    <span style="color:#a6e22e">data</span> <span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Pointer</span>
}
</code></pre></div><p>你会发现 interface 不是单纯的值，而是<strong>分为类型和值</strong>。</p>
<p>所以传统认知的此 nil 并非彼 nil，<strong>必须得类型和值同时都为 nil 的情况下，interface 的 nil 判断才会为 true</strong>。</p>
<h2 id="解决办法">解决办法</h2>
<p>与其说是解决方法，不如说是委婉的破局之道。在不改变类型的情况下，方法之一是利用反射（reflect），如下代码：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-golang" data-lang="golang"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
    <span style="color:#66d9ef">var</span> <span style="color:#a6e22e">data</span> <span style="color:#f92672">*</span><span style="color:#66d9ef">byte</span>
    <span style="color:#66d9ef">var</span> <span style="color:#a6e22e">in</span> <span style="color:#66d9ef">interface</span>{}

    <span style="color:#a6e22e">in</span> = <span style="color:#a6e22e">data</span>
    <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#a6e22e">IsNil</span>(<span style="color:#a6e22e">in</span>))
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">IsNil</span>(<span style="color:#a6e22e">i</span> <span style="color:#66d9ef">interface</span>{}) <span style="color:#66d9ef">bool</span> {
    <span style="color:#a6e22e">vi</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">ValueOf</span>(<span style="color:#a6e22e">i</span>)
    <span style="color:#66d9ef">if</span> <span style="color:#a6e22e">vi</span>.<span style="color:#a6e22e">Kind</span>() <span style="color:#f92672">==</span> <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">Ptr</span> {
        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">vi</span>.<span style="color:#a6e22e">IsNil</span>()
    }
    <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">false</span>
}
</code></pre></div><p>利用反射来做 nil 的值判断，在反射中会有针对 interface 类型的特殊处理，最终输出结果是：true，达到效果。</p>
<p>其他方法的话，就是改变原有的程序逻辑，例如：</p>
<ul>
<li>对值进行 nil 判断，再返回给 interface 设置。</li>
<li>返回具体的值类型，而不是返回 interface。</li>
</ul>
<h2 id="总结">总结</h2>
<p>Go interface 是 Go 语言中最常用的类型之一，大家用惯了 <code>if err != nil</code> 就很容易顺手就踩进去了。</p>
<p>建议大家要多留个心眼，如果对 interface 想要有更进一步的了解，可以看看我的这篇深入解析的文章：《一文吃透 Go 语言解密之接口 interface》。</p>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/go-tips-defer/">Go 群友提问：学习 defer 时很懵逼，这道不会做！</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/go-tips-lenstr/">问个 Go 问题，字符串 len 为 0 和 字符串为空 ，有啥区别？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/go-tips-goroutinenums/">Go 群友提问：Goroutine 数量控制在多少合适，会影响 GC 和调度？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/go-typeparams-master/">令人激动！Go 泛型代码合入 master（附尝鲜方法）</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/go-why-path/">意见征集：Go1 要不要移除 GOPATH？</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            <li>
                                                <a href="/tags/%e9%9d%a2%e8%af%95%e9%a2%98" title="View all posts tagged match">面试题</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.site/posts/go/go-tips-defer/"
                                                    rel="prev">Go 群友提问：学习 defer 时很懵逼，这道不会做！</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.site/posts/go/go-tips-goroutineid/">Go 群友提问：进程、线程都有 ID，为什么 Goroutine 没有 ID？</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.site/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.vip All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>